package com.kingyea.mobilepolice.kim.service.impl;

import com.kingyea.mobilepolice.kim.bean.KimUserFriendsVo;
import com.kingyea.mobilepolice.kim.dao.KimUserFriendsMapper;
import com.kingyea.mobilepolice.kim.service.KimUserFriendsService;
import com.kingyea.mobilepolice.kim.task.KimSynPlanTask;
import com.kingyea.mobilepolice.kim.utils.ConnectionDB;
import com.kingyea.mobilepolice.kim.utils.MD5;
import com.kingyea.mobilepolice.system.Result;
import com.kingyea.mobilepolice.system.StateCode;
import com.kingyea.mobilepolice.user.bean.User;
import com.kingyea.mobilepolice.user.dao.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class KimUserFriendsServiceImpl implements KimUserFriendsService {

    private Logger logger = LoggerFactory.getLogger(KimUserFriendsServiceImpl.class);

    @Autowired
    private KimUserFriendsMapper userFriendsMapper;

    @Autowired
    private UserMapper userMapper;

    @Value("${kim-uam.user.password}")
    private String userPassword;

    @Value("${kim-uam.user.ecode}")
    private String eCode;

    private static List<User> usersTemp;

    /**
     * 通过用户ID获取好友列表
     *
     * @param userId
     * @return
     */
    @Override
    public Result<KimUserFriendsVo> getUserFriendsByUserId(String userId) {
        Result result = new Result();
        try {
            List<KimUserFriendsVo> userFriendsVos = this.userFriendsMapper.getUserFriendsVoByUserId(userId);
            result.setData(userFriendsVos);
        } catch (Exception e) {
            result.setCode(StateCode.SERVER_DATA_ERROR);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 用户同步
     *
     * @param connectionDB
     * @return
     */
    @Override
    public Result doUserDateSyn(ConnectionDB connectionDB) {

        // 同步开始运行
        KimSynPlanTask.isDo = 1;

        // 获取所有人
        List<User> userList = userMapper.searchAll();

        if(KimSynPlanTask.isGenerateFriends){
            usersTemp = new ArrayList<>();
            usersTemp = userList;
        }

        List<String> loginIdList = new ArrayList<>();

        // uam_user SQL
        List<String> uamUserSqlList = new ArrayList<>();
        // uam_user_account SQL
        List<String> uamUserAccountSqlList = new ArrayList<>();

        // uam_user 参数
        String password = MD5.encrypt(userPassword);
        Integer type = 1;
        Integer status = 1;
        String linkSeting = "{\"isShowNavigation\":\"1\"}";
        Integer secretLevel = 0;

        // uam_user_account 参数
        Integer accountType = 0; // 登录帐号类型，0：帐号，1：手机号
        Integer accountStatus = 1; // 状态，0：禁用，1:正常

        int i = 0;
        int userListSize = userList.size();
        String uamUserSql = "";
        String uamUserAcoutSql = "";
        for (int j = 0; j < userListSize; j++) {
            User u = userList.get(j);
            String loginId = u.getLoginId();
            if(loginId.equals("admin")){
                loginId = loginId+"-1";
            }
            // LOGINID 重复
            loginId = getLoginId(loginIdList, loginId,1);
            if (i == 0) {
                uamUserSql = "insert into uam_user " +
                        "(USER_ID,NAME,LOGIN_ID,PASSWORD,TYPE,STATUS,LINK_SETTING,E_Code,Secret_Level) " +
                        "values ";
                uamUserAcoutSql = "insert into uam_user_account " +
                        "(id,user_id,login_id,type,status,e_code) " +
                        "values ";
            }
            uamUserSql += "('" + u.getUserId() + "','" + u.getName() + "','" + loginId + "','" + password + "','" + type + "','" + status + "','" + linkSeting + "','" + eCode + "','" + secretLevel + "')";
            uamUserAcoutSql += "('" + UUID.randomUUID().toString().toLowerCase() + "','" + u.getUserId() + "','" + loginId + "','" + accountType + "','" + accountStatus + "','" + eCode + "')";

            if (i < 499 && j < (userListSize - 1)) {
                uamUserSql += ",";
                uamUserAcoutSql += ",";
                i++;
            } else if (i == 499 || j == (userListSize - 1)) {
                uamUserSqlList.add(uamUserSql);
                uamUserAccountSqlList.add(uamUserAcoutSql);
                i = 0;
                uamUserSql = "";
                uamUserAcoutSql = "";
            }
            loginIdList.add(loginId);
        }

        if(!CollectionUtils.isEmpty(uamUserSqlList)&&uamUserSqlList.size()>0) {
            connectionDB.executeUpdate("DELETE FROM uam_user WHERE e_code = 'kingyea'",null);
            uamUserSqlList.forEach(v -> {
                connectionDB.executeUpdate(v, null);
            });
        }

        if(!CollectionUtils.isEmpty(uamUserAccountSqlList)&&uamUserAccountSqlList.size()>0) {
            connectionDB.executeUpdate("DELETE FROM uam_user_account WHERE e_code = 'kingyea'", null);
            uamUserAccountSqlList.forEach(v -> {
                connectionDB.executeUpdate(v, null);
            });
        }

        // 同步结束
        KimSynPlanTask.isDo = 0;

        return new Result();
    }

    @Override
    public Result generateFriendsForTest() {

        logger.info("生成好友 S");

        List<String> userIds = usersTemp.stream().map(User::getUserId).collect(Collectors.toList());

        userIds.forEach(v->{
            userFriendsMapper.addFirends(v,userIds);
        });

        logger.info("生成好友 E");

        return new Result();
    }

    private String getLoginId(List<String> loginIdList, String loginId,int i) {
        String loginIdTemp;
        if (loginIdList.contains(loginId)) {
            loginIdTemp = loginId + "-"+i;
            if(loginIdList.contains(loginIdTemp)){
                i++;
                loginIdTemp = getLoginId(loginIdList,loginId,i);
            }
        }else{
            loginIdTemp = loginId;
        }
        return loginIdTemp;
    }
}
